package com.lumyc.singleton;

class TestSingleton{
    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance1 == instance2);
    }
}

//饿汉式，不懒加载，线程安全
class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton(){

    };
    public static Singleton getInstance(){
        return singleton;
    }
}

//懒汉式，懒加载，线程不安全
class Singleton1{
    private static Singleton1 singleton1;
    private Singleton1(){

    }
    public static Singleton1 getInstance(){
        if(singleton1 == null){
            singleton1 =  new Singleton1();
        }
        return singleton1;
    }
}

//懒汉式，懒加载，线程安全
class Singleton2{
    private static Singleton2 singleton2;
    private Singleton2(){

    }
    public static synchronized Singleton2 getInstance(){
        if(singleton2 == null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
}

//双检锁，懒加载，线程安全
class Singleton3{
    private volatile static Singleton3 singleton3;
    private Singleton3(){

    }
    public static Singleton3 getInstance(){
        if (singleton3 == null) {
            synchronized (Singleton3.class){
                if (singleton3 == null) {
                    singleton3 = new Singleton3();
                }
            }
        }
        return singleton3;
    }
}